package com.axend.aerosense.dev.viewmodel;

import android.text.TextUtils;

import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.launcher.ARouter;
import com.axend.aerosense.base.bean.BaseDevInfoBean;
import com.axend.aerosense.base.impl.IBaseView;
import com.axend.aerosense.base.impl.ILoadDataResult;
import com.axend.aerosense.base.storage.MmkvHelper;
import com.axend.aerosense.base.viewmodel.CustomBaseViewModel;
import com.axend.aerosense.common.UrlApi;
import com.axend.aerosense.common.config.Gobal;
import com.axend.aerosense.common.router.RouterActivityPath;
import com.axend.aerosense.common.services.ILoginService;
import com.axend.aerosense.common.services.config.ServicesConfig;
import com.axend.aerosense.common.util.JsonUtil;
import com.axend.aerosense.dev.R;
import com.axend.aerosense.base.bean.ChooseDeviceBean;
import com.axend.aerosense.network.EasyHttp;
import com.axend.aerosense.network.cache.model.CacheMode;
import com.axend.aerosense.network.callback.SimpleCallBack;
import com.axend.aerosense.network.exception.ApiException;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;

import io.reactivex.disposables.Disposable;

public class ChooseDeviceViewModel extends CustomBaseViewModel<ChooseDeviceBean> {

    /**
     * 自动搜索标志：
     * 0：搜索中，显示动画
     * 1：搜索到结果，显示搜索到的设备列表
     * 2：搜索超时（在规定时间内未搜索到设备），显示超时图标
     */
    public MutableLiveData<Integer> searchFlag = new MutableLiveData<>(0);
    /**
     * 是否在搜索中
     */
    public MutableLiveData<Boolean> isSearch = new MutableLiveData<>(false);

    @Autowired(name = ServicesConfig.User.LONGING_SERVICE)
    ILoginService iLoginService;
    private Disposable disposable;

    public ChooseDeviceViewModel(IBaseView baseViewImpl, ILoadDataResult<ChooseDeviceBean> loadDataResultImpl) {
        super(baseViewImpl, loadDataResultImpl);
        ARouter.getInstance().inject(this);
    }

    /**
     * 获取设备连接的服务器IP和端口
     */
    public void getRadarTcpServer() {
        disposable = EasyHttp.post(UrlApi.URL.GetRadarTcpServer.getUrl())
                .headers("token", iLoginService.getToken())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<Object>() {
                    @Override
                    public void onTokenExpire() {
                        ToastUtils.showShort(R.string.common_login_first);
                        //登录界面不做处理
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(Object bean) {
                        LogUtils.d("TCP Server Address: ", bean);
                        String data = bean.toString();
                        if (!TextUtils.isEmpty(data) && data.contains(",")) {
//                            String[] split = data.split(",");
//                            String ip = split[0];
//                            int port = Integer.parseInt(split[1]);
//                            if (RegexUtils.isIP(ip) && (port >= 1 && port <= 65535)){
//
//                            }
                            //设备的服务器IP端口 保存到本地
                            MmkvHelper.getInstance()
                                    .getMmkv()
                                    .encode(Gobal.SAVE_KEY.RADAR_TCP_SERVICE_ADDRESS, data);
                        } else {
                            LogUtils.e("设备的服务器IP端口验证失败！");
                        }
                    }
                });
    }

    @Override
    public void onLoad() {
        disposable = EasyHttp.post(UrlApi.URL.GetRadarType.getUrl())
                .headers("token", iLoginService.getToken())
                .cacheMode(CacheMode.NO_CACHE)
                .upJson(JsonUtil.toJson(new BaseDevInfoBean()))
                .execute(new SimpleCallBack<ChooseDeviceBean>() {
                    @Override
                    public void onTokenExpire() {
                        com.blankj.utilcode.util.ToastUtils.showShort(R.string.common_login_first);
                        //登录界面不做处理
                        ARouter.getInstance().build(RouterActivityPath.Login.PAGE_LOGIN_HOME).withBoolean("jumpMainPage", true).greenChannel().navigation();
                    }

                    @Override
                    public void onError(ApiException e) {
                        ToastUtils.showShort(e.getMessage());
                        loadDataFail(e.getMessage());
                    }

                    @Override
                    public void onSuccess(ChooseDeviceBean deviceBean) {
                        loadDataSuccess(deviceBean);
                        getRadarTcpServer();
                    }
                });
    }




    @Override
    protected void onCleared() {
        super.onCleared();
        if (null != disposable) {
            disposable.dispose();
        }
    }
}
